package com.homework13;

import java.io.*;
import java.util.Scanner;
import java.util.UUID;

public class Main {

    public static void main(String[] args) {
        System.out.println("请输入一个文件夹路径:");
        Scanner sc = new Scanner(System.in);
        File file = new File(sc.nextLine());
        if(file.isDirectory()){
            int count = copyFile(file);
            System.out.println("总共复制了"+count+"个java文件");
            System.out.println("D:\\java目录下有"+new File("D:\\java").listFiles().length+"个Java文件");
        }else{
            System.out.println("该路径下的目录不是文件夹或文件夹不存在");
        }
    }

    public static int copyFile(File dir){
        int count = 0;
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try{
            File[] files = dir.listFiles(file -> file.getName().endsWith(".java") || file.isDirectory());
            for (File file : files) {
                if(file.isFile()){
                    count++;
                    fis = new FileInputStream(file);
                    //判断文件夹是否存在
                    File f = new File("D:\\java");
                    if(!f.isDirectory()){
                        f.mkdirs();
                    }
                    //判断文件是否存在
                    f = new File("D:\\java",file.getName());
                    if(f.exists()){
                        String fileName = file.getName();
                        fileName = fileName.substring(0,fileName.lastIndexOf("."));
                        String suffix = file.getName();
                        suffix = suffix.substring(suffix.lastIndexOf("."));
                        f = new File("D:\\java",fileName+UUID.randomUUID().toString()+suffix);
                    }
                    //往文件写入数据
                    fos = new FileOutputStream(f);
                    byte[] bytes = new byte[1024];
                    int i;
                    while(-1 != (i = fis.read(bytes))){
                        fos.write(bytes,0,i);
                    }
                    fos.close();
                    fis.close();
                }else{
                    count += copyFile(file);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return count;
    }
}
